package com.yidu.ruifeng_logistics.controller;

import com.yidu.ruifeng_logistics.entity.LogisticsArea;
import com.yidu.ruifeng_logistics.service.LogisticsAreaService;
import com.yidu.ruifeng_logistics.vo.TreeNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 地区表(LogisticsArea)表控制层
 *
 * @author makejava
 * @since 2021-03-09 14:24:36
 */
@Api(description = "瑞丰物流地区")
@RestController
@RequestMapping("logisticsArea")
public class LogisticsAreaController {
    /**
     * 服务对象
     */
    @Resource
    private LogisticsAreaService logisticsAreaService;

    @Resource
    RedisTemplate redisTemplate ;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public LogisticsArea selectOne(Integer id) {
        return this.logisticsAreaService.queryById(id);
    }



    @ApiOperation(value = "查询第一级", notes = "返回json")
    @GetMapping("selectYi")
    public List<TreeNode> selectYiJi(){
        List<TreeNode> treeNodes   = (List<TreeNode>)redisTemplate.opsForValue().get("areaTree");
        if(treeNodes==null) {
            treeNodes = new ArrayList<>();
            List<LogisticsArea> logisticsAreas = logisticsAreaService.selectEr(1);
            for (int i = 0; i < logisticsAreas.size(); i++) {
                TreeNode treeNode = new TreeNode();
                treeNode.setId(logisticsAreas.get(i).getAreaId());// 第一级ID
                treeNode.setName(logisticsAreas.get(i).getAreaName());
                treeNode.setOpen(false);
                treeNode.setChildren(selectE(logisticsAreas.get(i).getAreaId()));
                treeNodes.add(treeNode);
            }
            redisTemplate.opsForValue().set("areaTree",treeNodes);
        }
        return treeNodes;
    }

    /**
     * 树形递归
     * @param areaId
     * @return
     */
    public List<TreeNode> selectE(Integer areaId){
        List<TreeNode> list=new ArrayList<>();
        List<LogisticsArea> areas = logisticsAreaService.selectEr(areaId);
        for (int i = 0; i < areas.size(); i++) {
            TreeNode treeNode=new TreeNode();
            treeNode.setId(areas.get(i).getAreaId());// 第一级ID
            treeNode.setName(areas.get(i).getAreaName());
            treeNode.setOpen(false);
            if (areaId!=areas.get(i).getAreaUp()){
                return list;
            }else {
                treeNode.setChildren(selectE(areas.get(i).getAreaId()));//递归
                list.add(treeNode);
            }
        }
        return list;
    }

}
